import { SECOND_MILL } from '../constants';
import { DetState, HomeResponse } from '../service/interface';

type HandleCoinData = {
    balance: number;
    cycle: {
        real: number; // maybe float
        additionTime: number // Extra time beyond the whole circle.
    };
    stopTime: number; // second
    start: boolean;
}
export const handleCoinTimerData = (data: HomeResponse): HandleCoinData => {
    const lastTime = data.startTime;
    const serverTime = data.sysTime // millisecond
    const stopMills = data.endTime;

    const secondPerCycle = Number(data.detector.speedRate || 1);

    const leftTime = stopMills - serverTime;
    const start = data?.detState === DetState.working;

    if (!start || !lastTime || !serverTime || leftTime <= 0) {
        const c = Number(data.detector.cycleLength);
        return {
            balance: Number(data.balance || 0),
            cycle: {
                real: c,
                additionTime: 0,
            },
            stopTime: 0,
            start: false
        }
    }

    let time = 0;
    if (stopMills > serverTime) {
        time = (stopMills - serverTime) / SECOND_MILL;
    }


    const cycle = time / Number(data.detector.speedRate); // left cycle
    const additionTime = time % Number(data.detector.speedRate);
    const leftCycle = Math.min(cycle, Number(data.detector.cycleLength)) // if left 1.3 return 2
    const diffCycle = (serverTime - lastTime) / SECOND_MILL / secondPerCycle
    const currentCount = Number(data.balance) + Math.floor(diffCycle) * data.detector.realDetPower // Calculate only whole circle values.
    return {
        start,
        stopTime: time,
        balance: currentCount,
        cycle: {
            real: leftCycle,
            additionTime
        }
    }
}